package il.ac.bgu.cs.heuristics.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import org.apache.log4j.Logger;

public final class IOUtils {
	private final static String	PROJECT_PACKAGE_DIR	= "/il/ac/bgu/cs/heuristics";
	private final static Logger	LOG					= Logger
															.getLogger(IOUtils.class);

	private IOUtils() {
	} // no instantiation

	public static File getFile(String path) {
		String s = toAbsoluteProjectPath(path);
		Validation.ensureArgumentContainsText(path);
		final URL fileLocation = IOUtils.class.getResource(s);
		File f = null;
		if (fileLocation != null) {

			try {
				f = new File(fileLocation.toURI());
			} catch (URISyntaxException e) {
				LOG.error("error creating file ", e);
			}
		}
		return f;
	}

	public static InputStream getInputStream(String path) {
		return IOUtils.class.getResourceAsStream(toAbsoluteProjectPath(path));
	}

	public static Properties getProperties(String path) {
		final String resourcePath = toAbsoluteProjectPath(path);
		final InputStream in = IOUtils.class.getResourceAsStream(resourcePath);
		final Properties properties = new Properties();
		if (in == null) {
			LOG.error("resource wansn't found - (" + resourcePath + ")");
		} else {
			try {
				properties.load(in);
			} catch (IOException e) {
				LOG.error("error loading properties file from input stream - ",
						e);
			}
		}
		return properties;
	}

	private static String toAbsoluteProjectPath(String path) {
		if (path.startsWith(PROJECT_PACKAGE_DIR)) {
			return path;
		} else {
			if (path.charAt(0) == '/') {
				return PROJECT_PACKAGE_DIR + path;
			} else {
				return PROJECT_PACKAGE_DIR + "/" + path;
			}
		}
	}
}
